package com.todo.strategy.online.application.frontend.service.impl;

import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.enums.biz.PrivateTypeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.DateUtils;
import com.todo.strategy.common.enums.PlanRelationSceneEnum;
import com.todo.strategy.common.enums.StrategyRelationTypeEnum;
import com.todo.strategy.online.application.convert.StrategyConvert;
import com.todo.strategy.online.application.entity.bo.PlanRelationBO;
import com.todo.strategy.online.application.entity.bo.PlanSetBO;
import com.todo.strategy.online.application.frontend.service.PlanRelationAggService;
import com.todo.strategy.online.application.remote.UserInfoRemoteService;
import com.todo.strategy.online.application.service.PlanRelationService;
import com.todo.strategy.online.application.service.PlanSetService;
import com.todo.strategy.online.iface.request.*;
import com.todo.strategy.online.iface.response.PlanRelationDetailVO;
import com.todo.strategy.online.iface.response.SamplePlanSetVO;
import com.todo.user.api.response.BaseUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * (PlanRelation)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:47
 */
@Slf4j
@Service("planRelationAggService")
public class PlanRelationAggServiceImpl implements PlanRelationAggService {

    @Resource
    private PlanSetService planSetService;
    @Resource
    private PlanRelationService planRelationService;
    @Resource
    private UserInfoRemoteService userInfoRemoteService;

    @Override
    public BizResponse<Boolean> insertPlanRelation(InsertPlanRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        PlanRelationBO request = StrategyConvert.convertToPlanRelationBO(param);
        Boolean insertResult = planRelationService.insertPlanRelation(request);
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> duplicatePlanRelation(DuplicatePlanRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        if (!planSetBO.getUserId().equals(param.get_user().getUserId())) {
            throw new BizException(BizErrorCodeEnum.INSUFFICIENT_USER_PERMISSIONS, "无权修改他人计划");
        }
        List<PlanRelationBO> planRelationBOList = StrategyConvert.convertToPlanRelationBOList(param);
        Boolean insertResult = planRelationService.insertPlanRelationList(planRelationBOList);
        return BizResponse.success(insertResult);
    }

    @Override
    @Transactional
    public BizResponse<Boolean> duplicatePlanSet(DuplicatePlanSetParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        PlanSetBO duplicatePlanSet = StrategyConvert.buildDuplicatePlanSetBO(planSetBO);
        duplicatePlanSet.setUserId(param.get_user().getUserId());
        Boolean planSetResult = planSetService.insertPlanSet(duplicatePlanSet);
        if (!planSetResult) {
            return BizResponse.operationFailed("创建计划失败，请刷新后重试");
        }
        List<PlanRelationBO> planRelationBOList = planRelationService.queryPlanRelationByBizId(param.getPlanId(), PlanRelationSceneEnum.USER_STRATEGY);
        if (planRelationBOList == null) {
            return BizResponse.success();
        }
        Long newPlanId = duplicatePlanSet.getPlanId();
        List<PlanRelationBO> requestList = StrategyConvert.buildDuplicatePlanRelationBO(planRelationBOList, newPlanId);
        Boolean insertResult = planRelationService.insertPlanRelationList(requestList);
        log.info("PlanRelationAggService#duplicatePlanSet 复制保存清单计划完成，清单计划Id：【{}】，复制后数据：【{}】", param.getPlanId(), newPlanId);
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> updatePlanRelation(UpdatePlanRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        if (!planSetBO.getUserId().equals(param.get_user().getUserId())) {
            throw new BizException(BizErrorCodeEnum.INSUFFICIENT_USER_PERMISSIONS, "无权修改他人计划");
        }
        PlanRelationBO request = StrategyConvert.convertToPlanRelationBO(param);
        Boolean updateResult = planRelationService.updatePlanRelation(request);
        return BizResponse.success(updateResult);
    }

    @Override
    public BizResponse<Boolean> removePlanRelation(RemovePlanRelationParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        if (!planSetBO.getUserId().equals(param.get_user().getUserId())) {
            throw new BizException(BizErrorCodeEnum.INSUFFICIENT_USER_PERMISSIONS, "无权删除他人计划");
        }
        Boolean removeResult = planRelationService.removePlanRelationByIdList(param.getPlanId(), PlanRelationSceneEnum.USER_STRATEGY, param.getPlanRelationIdList());
        return BizResponse.success(removeResult);
    }

    @Override
    public BizResponse<SamplePlanSetVO> buildSamplePlanSetInfo(SamplePlanSetInfoParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        BizResponse<BaseUserInfoResponse> userAccountResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(planSetBO.getUserId());
        if (userAccountResponse == null || !userAccountResponse.isSuccess() || userAccountResponse.getData() == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        if (!userAccountResponse.getData().getUserId().equals(param.get_user().getUserId()) && PrivateTypeEnum.PRIVATE.equals(planSetBO.getIsPrivate())) {
            return BizResponse.success();
        }
        Map<Integer, List<PlanRelationBO>> integerListMap = planRelationService.queryPlanRelationMapByBizId(param.getPlanId(), PlanRelationSceneEnum.USER_STRATEGY);
        if (MapUtils.isEmpty(integerListMap)) {
            return BizResponse.success();
        }
        List<String> samplePlanList = new ArrayList<>();
        int diffDays = DateUtils.differentDaysByMillisecond(planSetBO.getStartPlanTime(), planSetBO.getEndPlanTime());
        for (int i = 1; i < diffDays; i++) {
            String temp = "第 %s 天计划：%s";
            List<PlanRelationBO> planRelationResponses = integerListMap.get(i);
            if (CollectionUtils.isEmpty(planRelationResponses)) {
                String desc = String.format(temp, i, "暂无计划");
                samplePlanList.add(desc);
                continue;
            }
            StringJoiner travelDesc = new StringJoiner("  ->  ");
            StringJoiner itemDesc = new StringJoiner("  |  ");
            for (PlanRelationBO planRelationBO : planRelationResponses) {
                itemDesc.add(planRelationBO.getTitle());
                if (StrategyRelationTypeEnum.CUSTOM.equals(planRelationBO.getRelationType())) {
                    if (planRelationBO.getExtra() != null && planRelationBO.getExtra().getCustomInfo() != null) {
                        itemDesc.add(planRelationBO.getExtra().getCustomInfo().getName());
                    }
                } else {
                    if (planRelationBO.getRelationName() != null) {
                        itemDesc.add(planRelationBO.getRelationName());
                    }
                }
                travelDesc.add(itemDesc.toString());
            }
            String desc = String.format(temp, i, travelDesc);
            samplePlanList.add(desc);
        }

        SamplePlanSetVO samplePlanSetVO = new SamplePlanSetVO();
        samplePlanSetVO.setSamplePlanList(samplePlanList);
        return BizResponse.success(samplePlanSetVO);
    }

    @Override
    public BizResponse<PlanRelationDetailVO> queryPlanRelationByPlanId(QueryPlanRelationByPlanIdParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PlanSetBO planSetBO = planSetService.queryPlanSetById(param.getPlanId());
        if (planSetBO == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        BizResponse<BaseUserInfoResponse> userAccountResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(planSetBO.getUserId());
        if (userAccountResponse == null || !userAccountResponse.isSuccess() || userAccountResponse.getData() == null) {
            return BizResponse.operationFailed("当前数据不存在，请刷新后重试");
        }
        if (!userAccountResponse.getData().getUserId().equals(param.get_user().getUserId()) && PrivateTypeEnum.PRIVATE.equals(planSetBO.getIsPrivate())) {
            return BizResponse.success();
        }
        List<PlanRelationBO> planRelationBOList = planRelationService.queryPlanRelationByBizId(param.getPlanId(), PlanRelationSceneEnum.USER_STRATEGY);
        return BizResponse.success(StrategyConvert.buildPlanRelationDetailVO(userAccountResponse.getData(), planSetBO, planRelationBOList));
    }

}
